/**
* Background script of Google Checker Chrome Extension
* Author: cjls1(cjls_1@g163.com) 2012/12/02
*/

var state = 'open';
var enabled = true;
var totalTab = 1;

function initState() {
    state = localStorage['state'] ? localStorage['state'] : 'open';
    enabled = (state == 'open');
}

function setState(enabled) {
    localStorage['state'] = enabled ? "open" : "close";
    chrome.browserAction.setIcon({
        path : enabled 
            ? "icon_enabled.png" 
            : "icon_disabled.png"});
    chrome.browserAction.setTitle({
        title : enabled 
            ? "Enable Google Checker" 
            : "Disable Google Checker"});
}

chrome.browserAction.onClicked.addListener(function(tab){
    enabled = !enabled;
    setState(enabled);
});

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
		if (request.target == 'background') {
			if (request.action == 'state') {
				if (enabled) {
					if (request.tabNum)
						totalTab = request.tabNum+1;
					totalTab++;
				}
				sendResponse({state: localStorage['state'], tabid: totalTab});
				return;
			}
		}
        sendResponse({});
    });
	
initState();
setState(enabled);
	
function redirectRequest(request) {
	if (!enabled)
		return;
		
	var urlTmp = request.url;

	//Is this a google url?
	var pos = urlTmp.indexOf("www.google.");
        //TODO: Because google domain is always banned. Use IP address to acccess it directly.
        //      Make IP address a configurable list.
	if (pos < 0){
		pos = urlTmp.indexOf("58.176.217.12");
		if (pos < 0){
				return;
			}
	}
	
	//need redirect?
	pos = urlTmp.indexOf("&gs_l=hp");
	if (pos < 0){
		pos = urlTmp.indexOf("&bav=");
		if (pos < 0)
			return;
	}
	urlTmp = urlTmp.substring(0, pos).replace(/#/,"search?");

	return { redirectUrl: urlTmp }
}

chrome.webRequest.onBeforeRequest.addListener(
	redirectRequest, 
	{ urls: ['http://*/*', 'https://*/*'] }, 
	['blocking']
);
